// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request-promise')

cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
const logger = cloud.logger()
const config_db = cloud.database().collection('config')
const visitor_db = cloud.database().collection('visitor')
const weather_db = cloud.database().collection('weather')

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case "home":
    case "mine":
      return getConfigData(event)
      break;
    case "weather":
      return getWeatherData(event)
      break;
    case "updateUserInfo":
      return updateVistorInfo(event);
      break;
    default:
      return {
        data: "请添加参数：action"
      };
      break;
  }
}


//获取Config数据
async function getConfigData(event) {
  const wxContext = cloud.getWXContext()
  var result = {}
  var onlineData = await config_db.where({
    flag: 'onlineStatus'
  }).get()
  //上线标识数据
  if (onlineData.data.length < 0) {
    result.data = "没有添加flag:onlineStatus标签"
  } else {
    var onling = onlineData.data[0].onling

    var whereCon = {
      flag: event.action
    }
    if (onling) whereCon.onlineCheck = true
    result = await config_db.where(whereCon).get()
    result.onling = onling
  }
  result.openid = wxContext.OPENID
  return result
}


//获取天气数据
async function getWeatherData(event) {
  const wxContext = cloud.getWXContext()
  var userInfo = event.userInfo
  var addressInfo = event.addressInfo
  let mOpenid = wxContext.OPENID
  var date_time = event.date_time //2020-03-01 15:15:11
  var city_name = event.city_name
  var dateTime = date_time.split(' ')[0] //2020-03-01
  var weather_list = await getWeatherDb(city_name, dateTime)
  // logger.error({
  //   getWeatherData_weather_list: weather_list,
  //   city_name: city_name,
  //   date_time: date_time
  // })
  //保存用户到数据库
  if (mOpenid != 'oC_xc5SmwHu-C-Lw_pS8Jv_hWmVk')
    saveUserDb(userInfo, addressInfo, date_time)
  //获取天气数据
  if (weather_list.length != 0) {
    return weather_list[0]
  } else {
    return getWeatherApi(city_name, dateTime)
  }
}


//获取天气数据库数据
async function getWeatherDb(city_name, date_time) {
  var whereCon = {
    city: city_name,
    date_time: date_time
  }
  var weather = await weather_db.where(whereCon).get()
  return weather.data;
}


//获取天气接口数据
async function getWeatherApi(city_name, date_time) {
  var weatherUrl = 'http://apis.juhe.cn/simpleWeather/query?key=63e112f49617054c7c4b0e1627a7723f';
  var options = {
    method: 'POST',
    uri: weatherUrl,
    form: {
      city: city_name
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  };
  var res = request(options).then(html => {
    // logger.error({
    //   getWeatherApi: html
    // })
    var weatherObj = JSON.parse(html).result
    //给天气对象添加时间属性
    weatherObj.date_time = date_time
    saveWeatherDb(weatherObj)
    return weatherObj;
  }).catch(err => {
    console.log(err);
  })
  return res
}


//保存天气数据到数据库
async function saveWeatherDb(weatherObj) {
  // logger.error({
  //   saveWeatherDb_weatherObj: weatherObj
  // })
  weatherObj.future = ""
  return await weather_db.add({
    data: weatherObj
  })
}

//保存用户数据到数据库
async function saveUserDb(userInfo, addressInfo, date_time) {
  const wxContext = cloud.getWXContext()
  var userObj = {
    flag: 'user',
    userInfo: userInfo,
    dateTime: date_time,
    addressInfo: addressInfo,
    _openid: wxContext.OPENID
  }
  logger.error({
    saveUserDb_userObj: userObj
  })
  return await visitor_db.add({
    data: userObj
  })
}


//更新用户信息
async function updateVistorInfo(event) {
  const wxContext = cloud.getWXContext()
  return await visitor_db.where({
    _openid: wxContext.OPENID
  }).update({
    data: {
      userInfo: event.userInfo
    }
  })
}
